package com.sgs.soda.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sgs.soda.core.GeneralResult;
import com.sgs.soda.core.auth.JwtTokenService;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 将登录用户的JWT转化成用户信息的全局过滤器
 * 全局过滤器AuthGlobalFilter，当鉴权通过后将JWT令牌中的用户信息解析出来，然后存入请求的Header中，这样后续服务就不需要解析JWT令牌了，可以直接从请求的Header中获取到用户信息。
 * @author Tim_Tian
 * @date 2021/7/21 18:04
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private JwtTokenService jwtTokenService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        if (StringUtils.startsWith(path, "/auth")){
            return chain.filter(exchange);
        }

        String token = exchange.getRequest().getHeaders().getFirst("Authorization");


        ServerHttpResponse resp = exchange.getResponse();
        if (StringUtils.isBlank(token)) {
            return authError(resp,"缺失令牌");
        }

        //从token中解析用户信息并设置到Header中去
        String realToken = token.replace(jwtTokenService.getTokenType(), "");

        Integer userId = jwtTokenService.getUserId(realToken);

        ServerHttpRequest request = exchange.getRequest().mutate().header("userId", userId.toString()).build();
        exchange = exchange.mutate().request(request).build();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 认证错误输出
     * @param resp 响应对象
     * @param message 错误信息
     * @return
     */
    private Mono<Void> authError(ServerHttpResponse resp,String message) {
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        GeneralResult<String> result = new GeneralResult<>();
        result.setStatus(500);
        result.setMessage(message);
        String returnStr = null;
        try {
            returnStr = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        DataBuffer buffer = resp.bufferFactory().wrap(returnStr.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

}
